package com.guiji.quartz.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guiji.common.annotation.Log;
import com.guiji.common.annotation.RepeatSubmit;
import com.guiji.common.core.controller.BaseController;
import com.guiji.common.core.domain.AjaxResult;
import com.guiji.common.core.page.TableDataInfo;
import com.guiji.common.enums.BusinessType;
import com.guiji.common.utils.poi.ExcelUtil;
import com.guiji.quartz.domain.SpiderNews;
import com.guiji.quartz.service.ISpiderNewsService;
import com.guiji.quartz.service.ISpiderNewsStatService;
import com.guiji.quartz.vo.SpiderNewsStatAddBo;
import com.guiji.quartz.vo.SpiderNewsStatEditBo;
import com.guiji.quartz.vo.SpiderNewsStatQueryBo;
import com.guiji.quartz.vo.SpiderNewsStatVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @create: 2021-09-15 17:37
 **/
@Api(value = "【请填写功能名称】控制器", tags = {"【请填写功能名称】管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/system/stat")
public class SpiderNewsStatController extends BaseController {

	private final ISpiderNewsStatService iSpiderNewsStatService;

	@Autowired
	private final ISpiderNewsService iSpiderNewsService;
	@GetMapping("/listaaaa")
	public void listaaa(@Validated SpiderNewsStatQueryBo bo) throws IOException {
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.like("news_category",bo.getNewsCategory());
		List<SpiderNews> list = iSpiderNewsService.listVo(queryWrapper, SpiderNews.class);
		for (SpiderNews spiderNews:list) {
			if(spiderNews.getNewsPicJson().contains("172.16.6.72")){
				continue;
			}
			String newsPicJson = spiderNews.getNewsPicJson();
			JSONArray jsonArray = JSONUtil.parseArray(newsPicJson);
			List<String> listPic = new ArrayList<>();
			for (Object img:jsonArray) {
				try {
					String name;
					if(img.toString().contains("gif")){
						continue;
					}else{
						name = UUID.randomUUID() + ".jpg";
					}

					String picPath = "/data/cms/dist/pic/" + bo.getNewsCategory() + "/" + name;
					HttpRequest.get(img.toString()).execute().writeBody(picPath);
//					OkHttpClient client = new OkHttpClient().newBuilder()
//						.build();
//					MediaType mediaType = MediaType.parse("text/plain");
//					okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType,new File(picPath));
//					Request request = new Request.Builder()
//						.url("http://172.16.160.57:8015/gen_pic_with_name/cutLogo")
//						.method("POST", body)
//						.build();
//					Response response = client.newCall(request).execute();
//					FileUtil.writeBytes(response.body().bytes(),new File(picPath));
					listPic.add("http://172.16.6.72/pic"+"/"+bo.getNewsCategory()+ "/" + name);
				} catch (Exception e) {
					continue;
				}
			}
			String picJSON = JSONUtil.toJsonStr(listPic);
			QueryWrapper removeMapper = new QueryWrapper();
			removeMapper.like("news_id",spiderNews.getNewsId());
			iSpiderNewsService.remove(removeMapper);
			spiderNews.setNewsPicJson(picJSON);
			iSpiderNewsService.save(spiderNews);
		}
	}


	/**
	 * 查询【请填写功能名称】列表
	 */
	@ApiOperation("查询【请填写功能名称】列表")
	@GetMapping("/list")
	public TableDataInfo<SpiderNewsStatVo> list(@Validated SpiderNewsStatQueryBo bo) {
		return iSpiderNewsStatService.queryPageList(bo);
	}

	/**
	 * 导出【请填写功能名称】列表
	 */
	@ApiOperation("导出【请填写功能名称】列表")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult<SpiderNewsStatVo> export(@Validated SpiderNewsStatQueryBo bo) {
		List<SpiderNewsStatVo> list = iSpiderNewsStatService.queryList(bo);
		ExcelUtil<SpiderNewsStatVo> util = new ExcelUtil<SpiderNewsStatVo>(SpiderNewsStatVo.class);
		return util.exportExcel(list, "【请填写功能名称】");
	}

	/**
	 * 获取【请填写功能名称】详细信息
	 */
	@ApiOperation("获取【请填写功能名称】详细信息")
	@GetMapping("/{id}")
	public AjaxResult<SpiderNewsStatVo> getInfo(@NotNull(message = "主键不能为空")
												@PathVariable("id") Long id) {
		return AjaxResult.success(iSpiderNewsStatService.queryById(id));
	}

	/**
	 * 新增【请填写功能名称】
	 */
	@ApiOperation("新增【请填写功能名称】")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
	@RepeatSubmit
	@PostMapping()
	public AjaxResult<Void> add(@Validated @RequestBody SpiderNewsStatAddBo bo) {
		return toAjax(iSpiderNewsStatService.insertByAddBo(bo) ? 1 : 0);
	}

	/**
	 * 修改【请填写功能名称】
	 */
	@ApiOperation("修改【请填写功能名称】")
	@Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping()
	public AjaxResult<Void> edit(@Validated @RequestBody SpiderNewsStatEditBo bo) {
		return toAjax(iSpiderNewsStatService.updateByEditBo(bo) ? 1 : 0);
	}

	/**
	 * 删除【请填写功能名称】
	 */
	@ApiOperation("删除【请填写功能名称】")
	@Log(title = "【请填写功能名称】" , businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")
								   @PathVariable Long[] ids) {
		return toAjax(iSpiderNewsStatService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
	}
}
